# coding:utf-8
import copy
import requests
import simplejson

CONNECT_TIMEOUT = 2  # 超时设定，单位秒


class GZ_Rest_Client(object):
    _cookies = None

    def __init__(self, url, name, password):
        self.url = url if url.endswith('/') else url + '/'
        self.name = name
        self.password = password

    def get_cookies(self):
        """
        返回浅拷贝的cookies，主要用于websocket连接时所需要的验证。
        :return: cookies
        """
        if self._cookies:
            return copy.copy(self._cookies)
        return self._cookies

        self.url = url

    def login(self):
        """
               登录，成功则记录cookies值使用
               :param name:
               :param password:
               :return:
               """
        login_url = self.url + 'bitmex/login/'
        params = {'name': self.name, 'password': self.password}
        res = requests.post(login_url, data=params, timeout=CONNECT_TIMEOUT)
        if res.status_code == 200:
            self._cookies = requests.utils.dict_from_cookiejar(res.cookies)
            return {"status_code": 200, "data": simplejson.dumps(res.text), "res": ""}
        else:
            return {"status_code": 500, "data": {}, "res": "请求错误"}

    def logout(self):
        login_url = self.url + 'bitmex/login/'
        params = {'name': self.name, 'password': self.password}
        res = requests.post(login_url, data=params, timeout=CONNECT_TIMEOUT)
        if res.status_code == 200:
            self._cookies = None
            return {"status_code": 200, "data": simplejson.loads(res.text), "res": ""}
        else:
            return {"status_code": 404, "data": {}, "res": "用户名或账号错误"}

    def get_bimex_api_key(self):
        if self._cookies:
            res = requests.get(self.url + "bitmex/get_api_key", cookies=self._cookies)
            if res.status_code == 200:
                data = simplejson.loads(res.text)
                return {"status_code": 200, "data": data, "res": ""}
            else:
                return {"status_code": res.status_code, "data": {}, "res": res["msg"]}
        else:
            return {"status_code": 403, "data": {}, "res": "请登陆"}


# 使用范例
if __name__ == '__main__':
    restApi = GZ_Rest_Client(url="http://front.jiafu.one/gz_server/", name='test', password='123456')
    res = restApi.login()
    print(restApi.get_cookies())
    print(restApi.get_bimex_api_key())
